package uploadServer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 * 
 * @author Tidus
 * @category: check file tai client. Format file != null --> Upload
 */

public class CheckImg {
		
	private static String getFormatName(Object obj) {
	    try {
	        // Create an image input stream on the image
	        ImageInputStream iis = ImageIO.createImageInputStream(obj);

	        // Find all image readers that recognize the image format
	        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
	        if (!iter.hasNext()) {
	            // No readers found
	            return null;
	        }

	        // Use the first reader
	        ImageReader reader = iter.next();
	        
	        // Close stream
	        iis.close();

	        // Return the format name
	        return reader.getFormatName();
	    } catch (IOException e) {
	    }
	    // The image could not be read
	    return null;
	}
	
	// Returns the format of the image in the file 'f'.
	// Returns null if the format is not known.
	public static String getFormatInFile(File f) {
	    return getFormatName(f);
	}

	// Returns the format of the image in the input stream 'is'.
	// Returns null if the format is not known.
	public static String getFormatFromStream(InputStream is) {
	    return getFormatName(is);
	}

	
//	public static void main(String args[]) throws IOException{
////	    File f = new File("C:\\Documents and Settings\\Tidus.SH\\Desktop\\At the Arch.jpg");
////	    System.out.println(CheckImg.getFormatInFile(f));
////	    //	dung inputStream
////	    InputStream is = new FileInputStream("C:\\Documents and Settings\\Tidus.SH\\Desktop\\At the Arch.jpg");
////	    System.out.println(CheckImg.getFormatName(is));
//	    
//	    String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
//	    System.out.println("FileSuffixes: ");
//	    for(int i =0; i < fileSuffixes.length; i++){
//	    	System.out.println("\t"+fileSuffixes[i]);
//	    }
//	    
//	    String[] formatNames = ImageIO.getReaderFormatNames();
//	    System.out.println("FormatNames: ");
//	    for(int i =0; i < formatNames.length; i++){
//	    	System.out.println("\t"+formatNames[i]);
//	    }
//	    
//	    String[] MIMETypes = ImageIO.getReaderMIMETypes();
//	    System.out.println("MIMETypes: ");
//	    for(int i =0; i < MIMETypes.length; i++){
//	    	System.out.println("\t"+MIMETypes[i]);
//	    }
//	}
	
}
